package com.health.viewscontrols.qyinfo;

import java.io.File;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.UUID;

import com.health.adapter.MemberRelationAdapter;
import com.health.adapter.SSQAdapter;
import com.health.viewscontrols.NovaApplication;
import com.health.viewscontrols.NovaFragmentActivity;
import com.health.R;
import com.health.adapter.FragmentAdapter;
import com.health.adapter.QYDoctersAdapter;
import com.health.viewscontrols.settings.DataDownLoadMainActivity;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tablebean.BD_DD_INFO;
import com.health.tablebean.BD_ORGANIZE_EMPLOYEE;
import com.health.tablebean.JTYSCustomerDoctorCont;
import com.health.tablebean.JTYS_BASEINFO;
import com.health.tablebean.JTYS_SignPictureData;
import com.health.tools.GlobalConts;
import com.health.tools.GlobalContsJTYS;
import com.health.tools.ImageTools;
import com.health.tools.SPUtil;
import com.health.viewscontrols.settings.DataSynchronizationMainActivity;
import com.health.viewscontrols.tupian.ClipActivity1;
import com.health.widget.CommomDialog;
import com.health.widget.EditTextWithDate;
import com.health.widget.MyViewPager2;
import com.health.widget.QyinfoMemLinearLayout;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.media.Image;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.Scroller;
import android.widget.Spinner;
import android.widget.TextView;

/**
 * 签约界面
 *
 * @author nova
 */
public class QYInfo extends NovaFragmentActivity implements OnClickListener, OnLongClickListener,MemberRelationAdapter.EventActionCallback {

    private static final String TAG = "QYInfo";
    private TextView detail_id_tv;
    private TextView detail_name_text;
    private TextView detail_nation_text;
    private TextView detail_date_tv;
    private TextView detail_sex_tv;
    private TextView detail_phone_edit;
    private TextView ht_no;
    private EditTextWithDate ed_date;
    private Spinner ed_sfysqm;
    private EditText doc_phone_edit;
    private ARCHIVE_BASEINFO userInfo = null;
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

    private MyViewPager2 viewPager;
    private ArrayList<RadioButton> radioButtons;
    private ArrayList<Fragment> fragments;
    private Button btn_back;
    private Button btn_save;
    private TextView title;
    QY_fwxmb_jcFragment jcFragment = null;
    QY_fwxmb_dfxzFragment dfxzFragment = null;
    QY_fwxmb_zzFragment zzFragement = null;
    Fragment bzFragement = null;
    private int flagSave = -1;

    public JTYSCustomerDoctorCont cont = null;
    private int pos_doc = 0;

    private ImageView img_patientsign;
    private ImageView img_doctorsign;
    private ImageView iv_photo1;
    private ImageView iv_photo2;
    private ImageView iv_photo3;

    private LinearLayout btn_patientsign;
    private LinearLayout btn_doctorsign;
    private LinearLayout btn_add_photo;
    // 患者
    private final int REQUEST_CODE_PATIENT = 11;
    // 医生
    private final int REQUEST_CODE_DOCTOR = 12;
    //
    private final int REQUEST_CODE_PHOTO = 13;

    //选择家庭成员
    private final int REQUEST_CODE_ADD_MEMBER= 14;

    //签约类型
    public   static  String signType = "";
    //签约类型 --  1个人签约
    public static final String SIGNTYPE_PERSONAL = "1";

    //签约类型 --  2家庭签约
    public static final String SIGNTYPE_FAMILY = "2";


    // 患者签名
    private String strPatientSignPath = "";

    // 医生签名
    private String strDocSignPath = "";

    // 上传签约照
    private List<String> lstPhotoPaths;

    /**
     * 服务开始时间
     */
    private EditTextWithDate ed_start_service;
    /**
     * 服务结束时间
     */
    private EditTextWithDate ed_stop_serverce;
    private String str = UUID.randomUUID().toString();
    String uuid = str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24, 30);

    String imagePath = Environment.getExternalStorageDirectory() + "/PublicHealth/images/";
    String signPath = Environment.getExternalStorageDirectory() + "/PublicHealth/Sign/";
    private ScrollView scrollView;

    /**
     *家庭医生签约类型
     */
    private RadioGroup qyinfo_type;

    /**
     * 个人
     */
    private RadioButton rb_qyinfo_type_personal;
    /**
     * 家庭
     */
    private RadioButton rb_qyinfo_type_family;
    /**
     * 添加按钮
     */
    private TextView tv_add_family_member;
    /**
     * 家庭成员 关系数据
     */
    private ListView list_member_data;
    /**
     *家庭关系列表
     */
    private  LinearLayout linear_content_add;
    /**
     * 家庭成员关系成员列表
     */
    private List<ARCHIVE_BASEINFO> relationsMembers=new ArrayList<>();
    /**
     * 关系成员
     */
    MemberRelationAdapter memberRelationAdapter=null;
    private LinearLayout llFinish;
    private TextView tvTitle;
    private Button bt_save;
    private ImageView iv_bg;
    private String patientsign;
    private String doctorsign;


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.qyinfo);
        userInfo = NovaApplication.getUserInfo();
        // Log.e("userInfo.getMINORITY()", userInfo.getMINORITY());
        if (NovaApplication.idCardTool != null) {
            NovaApplication.idCardTool.stopScanReceive();
        }
        lstPhotoPaths = new ArrayList<String>();

        addColumn();
        findViews();
        setListeners();
        setData();

    }

    /**
     * JTYS_KHQYB 添加 Createrorg beginservictime res2   三个字段
     */
    private void addColumn() {
        NovaApplication.dbManger.addColumnByBySQL("JTYS_KHQYB", "createrorg");
        NovaApplication.dbManger.addColumnByBySQL("JTYS_KHQYB", "beginservictime");
        NovaApplication.dbManger.addColumnByBySQL("JTYS_KHQYB", "res2");
        NovaApplication.dbManger.addColumnByBySQL("JTYS_KHQYB", "res3");
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.qy_jcfwb:
                viewPager.setCurrentItem(0);
                setChecked(0);
                break;
            case R.id.qy_dfxzfwb:
                viewPager.setCurrentItem(1);
                setChecked(1);
                break;
            case R.id.qy_zzfwb:
                viewPager.setCurrentItem(2);
                setChecked(2);
                break;
            case R.id.qy_bz:
                viewPager.setCurrentItem(3);
                setChecked(3);
                break;

            case R.id.btn_back:

                List<JTYSCustomerDoctorCont> conts = NovaApplication.fdbmanger.findAllByWhere(JTYSCustomerDoctorCont.class,
                        "cardNum='" + NovaApplication.getUserInfo().getIDCARD() + "'");
                if (conts == null) {

                    deleteCachePhotoFromSD();
                } else {
                    if (conts.size() == 0) {
                        deleteCachePhotoFromSD();
                    }
                }
                finish();
                break;
            case R.id.ll_finish:
                List<JTYSCustomerDoctorCont> conts2 = NovaApplication.fdbmanger.findAllByWhere(JTYSCustomerDoctorCont.class,
                        "cardNum='" + NovaApplication.getUserInfo().getIDCARD() + "'");
                if (conts2 == null) {

                    deleteCachePhotoFromSD();
                } else {
                    if (conts2.size() == 0) {
                        deleteCachePhotoFromSD();
                    }
                }
                finish();
                break;
            case R.id.btn_up:
                // 保存数据
                Log.w(TAG, "btn_saveeeeeeeeeeee");
                saveDatas();



                // Intent intent = new Intent(getApplicationContext(),
                // MainActivity_Menu_Settings.class);
                // startActivity(intent);
                break;

            case R.id.bt_save:
                saveDatas();
                break;

            case R.id.img_patientsign:
                // 患者签名

                break;
            case R.id.img_doctorsign:
                // 医生签名

                break;
            case R.id.btn_patientsign:
                // 患者签名btn
                if (userInfo != null) {
                    if (TextUtils.isEmpty(ed_date.getText().toString())) {
                        showTextDialog("请先选择签约日期");
                        return;
                    }

                    if ("重签".equals(patientsign)) {
                        judgeFileIsExistsAndDelete(strPatientSignPath);
                    }

                    Intent intent = new Intent(QYInfo.this, QianMingActivity.class);
                    // //命名规则： 身份证号_签约时间_用户类型_创建时间时分秒_随机数.png[用户类型： 1 医生 2 患者 3
                    // 其他图片]
                    intent.putExtra(QianMingActivity.SIGNNAME_HEAD, getPhotoPath("2"));
                    startActivityForResult(intent, REQUEST_CODE_PATIENT);
                } else {
                    showTextDialog("没有获取到用户数据");
                }
                break;
            case R.id.btn_doctorsign:
                // 医生签名btn
                if (userInfo != null) {
                    if (TextUtils.isEmpty(ed_date.getText().toString())) {
                        showTextDialog("请先选择签约日期");
                        return;
                    }

                    if ("重签".equals(doctorsign)) {
                        judgeFileIsExistsAndDelete(strDocSignPath);
                    }

                    Intent intent = new Intent(QYInfo.this, QianMingActivity.class);
                    // //命名规则： 身份证号_签约时间_用户类型_创建时间时分秒_随机数.png[用户类型： 1 医生 2 患者 3
                    // 其他图片]
                    intent.putExtra(QianMingActivity.SIGNNAME_HEAD, getPhotoPath("1"));
                    startActivityForResult(intent, REQUEST_CODE_DOCTOR);
                } else {
                    showTextDialog("没有获取到用户数据");
                }
                break;
            case R.id.btn_add_photo:
                if (userInfo != null) {
                    if (iv_photo1.getVisibility() == View.VISIBLE && iv_photo2.getVisibility() == View.VISIBLE
                            && iv_photo3.getVisibility() == View.VISIBLE) {
                        showTextDialog("最多拍摄三张照片");
                        return;
                    }
                    if (TextUtils.isEmpty(ed_date.getText().toString())) {
                        showTextDialog("请先选择签约日期");
                        return;
                    }
                    paizhao();
                } else {
                    showTextDialog("没有获取到用户数据");
                }
                break;
            case R.id.tv_add_family_member:
                Intent intent = new Intent(QYInfo.this,MemberDataActivity.class);
                startActivityForResult(intent,REQUEST_CODE_ADD_MEMBER);

                break;
            default:
                break;
        }
    }

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");

    /**
     * 客户身份证号_签约时间_用户类型_创建时间时分秒_随机数.png
     * <p>
     * 370883198806046521_2017-12-07_1_20171207104138_8140.png
     *
     * @param type 1 医生 签名 2 患者签名 3 其他照片
     * @return
     * @author 鹿云龙
     * @date 2017年12月26日 上午10:13:28
     */
    private String getPhotoPath(String type) {
        if (type == null) {
            return null;
        }
        String str = "";
        File file = null;
        switch (type) {
            case "1":
            case "2":
                file = new File(Environment.getExternalStorageDirectory() + "/PublicHealth/Sign/");
                str = Environment.getExternalStorageDirectory() + "/PublicHealth/Sign/" + userInfo.getIDCARD() + "_"
                        + ed_date.getText().toString() + "_" + type + "_" + sdf.format(new Date()) + "_"
                        + (int) ((Math.random() * 9 + 1) * 1000) + ".png";
                break;
            case "3":
                file = new File(Environment.getExternalStorageDirectory() + "/PublicHealth/images/");
                str = Environment.getExternalStorageDirectory() + "/PublicHealth/images/" + userInfo.getIDCARD() + "_"
                        + ed_date.getText().toString() + "_" + type + "_" + sdf.format(new Date()) + "_"
                        + (int) ((Math.random() * 9 + 1) * 1000) + ".png";
                break;
            default:
                file = new File(Environment.getExternalStorageDirectory() + "/PublicHealth/images/");
                str = Environment.getExternalStorageDirectory() + "/PublicHealth/images/" + userInfo.getIDCARD() + "_"
                        + ed_date.getText().toString() + "_" + type + "_" + sdf.format(new Date()) + "_"
                        + (int) ((Math.random() * 9 + 1) * 1000) + ".png";
                break;
        }
        if (!file.exists()) {
            file.mkdirs();
        }
        return str;
    }

    public void paizhao() {
        mPhotoPath = getPhotoPath("3");
        File mCurrentPhotoFile = new File(mPhotoPath);
        Intent intentC = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Build.VERSION_CODES.N
        if (Build.VERSION.SDK_INT >= 24) {
            Uri imageUri = FileProvider.getUriForFile(this, "com.health" + ".fileprovider", mCurrentPhotoFile);
            intentC.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intentC.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        } else {
            intentC.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCurrentPhotoFile));
        }
        startActivityForResult(intentC, REQUEST_CODE_PHOTO);
    }

    public void findViews() {
        ht_no = (TextView) findViewById(R.id.ht_no);
        llFinish = (LinearLayout)findViewById(R.id.ll_finish);
        tvTitle = (TextView)findViewById(R.id.tv_title);
        detail_id_tv = (TextView) findViewById(R.id.detail_id_tv);
        detail_name_text = (TextView) findViewById(R.id.detail_name_text);
        detail_nation_text = (TextView) findViewById(R.id.detail_nation_text);
        detail_date_tv = (TextView) findViewById(R.id.detail_date_tv);
        detail_sex_tv = (TextView) findViewById(R.id.detail_sex_tv);
        detail_phone_edit = (TextView) findViewById(R.id.detail_phone_edit);
        ed_date = (EditTextWithDate) findViewById(R.id.ed_date);
        ed_start_service = (EditTextWithDate) findViewById(R.id.ed_start_service);
        ed_stop_serverce = (EditTextWithDate) findViewById(R.id.ed_stop_serverce);
        ed_sfysqm = (Spinner) findViewById(R.id.ed_sfysqm);
        doc_phone_edit = (EditText) findViewById(R.id.doc_phone_edit);
        btn_back = (Button) findViewById(R.id.btn_back);
        btn_save = (Button) findViewById(R.id.btn_up);
        title = (TextView) findViewById(R.id.title);
        bt_save = (Button)findViewById(R.id.bt_save);
        title.setText("家庭医生服务签约协议");
        tvTitle.setText("家庭医生服务签约协议");
        btn_back.setOnClickListener(this);
        btn_save.setOnClickListener(this);
        llFinish.setOnClickListener(this);
        bt_save.setOnClickListener(this);

        viewPager = (MyViewPager2) findViewById(R.id.viewpager);
        RadioButton qy_jcfwb = (RadioButton) findViewById(R.id.qy_jcfwb);
        RadioButton qy_dfxzfwb = (RadioButton) findViewById(R.id.qy_dfxzfwb);
        RadioButton qy_zzfwb = (RadioButton) findViewById(R.id.qy_zzfwb);
        RadioButton qy_bz = (RadioButton) findViewById(R.id.qy_bz);
        radioButtons = new ArrayList<RadioButton>();
        radioButtons.add(qy_jcfwb);
        radioButtons.add(qy_dfxzfwb);
        radioButtons.add(qy_zzfwb);
        radioButtons.add(qy_bz);

        qy_jcfwb.setOnClickListener(this);
        qy_dfxzfwb.setOnClickListener(this);
        qy_zzfwb.setOnClickListener(this);
        qy_bz.setOnClickListener(this);

        jcFragment = new QY_fwxmb_jcFragment();
        dfxzFragment = new QY_fwxmb_dfxzFragment();
        zzFragement = new QY_fwxmb_zzFragment();
        bzFragement = new QY_fwxmb_bzFragment();
        fragments = new ArrayList<Fragment>();
        fragments.add(jcFragment);
        fragments.add(dfxzFragment);
        fragments.add(zzFragement);
        fragments.add(bzFragement);

        FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(adapter);
        setChecked(0);
        viewPager.setOffscreenPageLimit(4);

        bindSpinnerQyDocList(NovaApplication.getDoctorList());

        img_patientsign = (ImageView) findViewById(R.id.img_patientsign);
        img_doctorsign = (ImageView) findViewById(R.id.img_doctorsign);
        iv_photo1 = (ImageView) findViewById(R.id.iv_photo1);
        iv_photo2 = (ImageView) findViewById(R.id.iv_photo2);
        iv_photo3 = (ImageView) findViewById(R.id.iv_photo3);
        btn_patientsign = (LinearLayout) findViewById(R.id.btn_patientsign);
        btn_doctorsign = (LinearLayout) findViewById(R.id.btn_doctorsign);
        btn_add_photo = (LinearLayout) findViewById(R.id.btn_add_photo);
        scrollView = (ScrollView) findViewById(R.id.scrollView);
        iv_bg = (ImageView)findViewById(R.id.iv_bg);

        qyinfo_type = (RadioGroup) findViewById(R.id.qyinfo_type);
        rb_qyinfo_type_personal = (RadioButton) findViewById(R.id.qyinfo_type_personal);
        rb_qyinfo_type_family = (RadioButton) findViewById(R.id.qyinfo_type_family);
        tv_add_family_member= (TextView) findViewById(R.id.tv_add_family_member);
        tv_add_family_member.setVisibility(View.GONE);

        list_member_data=(ListView)findViewById(R.id.list_member_data);
        linear_content_add=(LinearLayout)findViewById(R.id.linear_content_add);
        linear_content_add.setVisibility(View.GONE);
    }

    public void setListeners() {
        img_patientsign.setOnClickListener(this);
        img_doctorsign.setOnClickListener(this);
        btn_patientsign.setOnClickListener(this);
        btn_doctorsign.setOnClickListener(this);
        btn_add_photo.setOnClickListener(this);
        tv_add_family_member.setOnClickListener(this);

        iv_photo1.setOnLongClickListener(this);
        iv_photo2.setOnLongClickListener(this);
        iv_photo3.setOnLongClickListener(this);
        int age = GlobalConts.getAge(userInfo.getBIRTHDAY());
        if(age<20){
            rb_qyinfo_type_family.setEnabled(false);
        }else{
            rb_qyinfo_type_family.setEnabled(true);
        }



        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                final int currentSelectedPosition = viewPager.getCurrentItem();
                View view = viewPager.getChildAt(currentSelectedPosition);
                if (view != null) {
                    int height = view.getMeasuredHeight();
                    android.widget.LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) viewPager
                            .getLayoutParams();
                    layoutParams.height = height;
                    viewPager.setLayoutParams(layoutParams);
                }
                radioButtons.get(position).setChecked(true);
                setChecked(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        ed_sfysqm.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                pos_doc = position;
                setSpinnerPos(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        qyinfo_type.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId==R.id.qyinfo_type_personal){
                    //个人
                    tv_add_family_member.setVisibility(View.GONE);
                    linear_content_add.setVisibility(View.GONE);
                    signType=SIGNTYPE_PERSONAL;
                }else if(checkedId==R.id.qyinfo_type_family){
                    //家庭
                    tv_add_family_member.setVisibility(View.VISIBLE);
                    linear_content_add.setVisibility(View.VISIBLE);
                    signType=SIGNTYPE_FAMILY;
                }
            }
        });

        ed_stop_serverce.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String cruuentDate=GlobalConts.dateFormat.format(new Date());

                if(TextUtils.isEmpty(ed_start_service.getText())){
                    showTextDialog("请先输入开始服务时间");
                }else if(!TextUtils.isEmpty(ed_stop_serverce.getText())&&ed_start_service.getText().toString().equals(ed_stop_serverce.getText().toString())){
                    showTextDialog("签约时间不合理，请重新核对下服务结束时间");
                    ed_stop_serverce.setText("");
                }else try {
                    if(!TextUtils.isEmpty(ed_stop_serverce.getText())&& GlobalConts.dateFormat.parse(ed_stop_serverce.getText().toString()).before(new Date())){
                        showTextDialog("签约时间不合理，请重新核对下服务结束时间");
                        ed_stop_serverce.setText("");
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            List<JTYSCustomerDoctorCont> conts = NovaApplication.fdbmanger.findAllByWhere(JTYSCustomerDoctorCont.class,
                    "cardNum='" + NovaApplication.getUserInfo().getIDCARD() + "'");
            if (conts == null) {

                deleteCachePhotoFromSD();
            } else {
                if (conts.size() == 0) {
                    deleteCachePhotoFromSD();
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void setData() {

        memberRelationAdapter= new MemberRelationAdapter(QYInfo.this,relationsMembers);
        memberRelationAdapter.setEventActionCallback(this);
        list_member_data.setAdapter(memberRelationAdapter);


        scrollView.smoothScrollTo(0,0);

        setDataContent();


    }








    @SuppressLint("ResourceAsColor")
    private void setChecked(int pos) {
        for (RadioButton rbtn : radioButtons) {
            rbtn.setBackgroundResource(R.drawable.service_bg2);
        }
        radioButtons.get(pos).setBackgroundResource(R.drawable.service_bg);
    }

    /**
     * 保存数据
     *
     * @author 王婷婷
     * @date 2017年5月31日 下午4:17:19
     */
    private void saveDatas() {
        if("1".equals(NovaApplication.getUserInfo().getDISTRICT_ID())){
            showTextDialog("您已签约，不能重复签约");
            return;
        }
        String qysj = ed_date.getText().toString();
        if (TextUtils.isEmpty(qysj)) {
            showTextDialog("请选择签约时间");
            return;
        }
        String qyStartsj = ed_start_service.getText().toString();
        if (TextUtils.isEmpty(qyStartsj)) {
            showTextDialog("请选择服务开始时间");
            return;
        }
        String qyStopsj = ed_stop_serverce.getText().toString();
        if (TextUtils.isEmpty(qyStopsj)) {
            showTextDialog("请选择服务结束时间");
            return;
        }

        if (compareData(qyStartsj, qyStopsj)) {
            ed_stop_serverce.setText("");
            showTextDialog("服务开始时间不能大于服务结束时间");
            return;
        }
        if(TextUtils.isEmpty(strPatientSignPath)){
            showTextDialog("请患者签名");
            return;
        }
        if(TextUtils.isEmpty(strDocSignPath)){
            showTextDialog("请医生签名");
            return;
        }
        if(lstPhotoPaths.size()<=0){
            showTextDialog("请上传签约照");
            return;
        }

        String ckid_jc = ((QY_fwxmb_jcFragment) jcFragment).getCheckIDs();
        String ckid_df = ((QY_fwxmb_dfxzFragment) dfxzFragment).getCheckIDs();
        String ckid_zz = ((QY_fwxmb_zzFragment) zzFragement).getCheckIDs();
        if (!hasServicePackage()) {
            new AlertDialog.Builder(QYInfo.this).setTitle(getString(R.string.alert_dialog_titile))// 设置对话框标题
                    .setMessage(getString(R.string.main_activity_message_1))// 设置显示的内容
                    .setPositiveButton(getString(R.string.enter), new DialogInterface.OnClickListener() {// 添加确定按钮
                        @Override
                        public void onClick(DialogInterface dialog, int which) {// 确定按钮的响应事件
                            startActivity(new Intent(QYInfo.this, DataSynchronizationMainActivity.class));
                        }
                    }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {// 添加返回按钮
                @Override
                public void onClick(DialogInterface dialog, int which) {// 响应事件
                }
            }).show();// 在按键响应事件中显示此对话框
            return;
        }
        if (TextUtils.isEmpty(ckid_zz) && TextUtils.isEmpty(ckid_df) && TextUtils.isEmpty(ckid_jc)) {
            showTextDialog("请选择服务项目");
            return;
        }

        //家庭类型 只能选择 基础服务包
        if(rb_qyinfo_type_family.isChecked()){
            if((!TextUtils.isEmpty(ckid_df) )||(!TextUtils.isEmpty(ckid_zz)) ){
                showTextDialog("以家庭为单位的签约只能选择基础服务包");
                return;
            }
        }
        String checkIds = ckid_jc + (TextUtils.isEmpty(ckid_df) ? "" : "," + ckid_df)
                + (TextUtils.isEmpty(ckid_zz) ? "" : "," + ckid_zz);
        Log.e(TAG, checkIds);
        Log.e("tag", "checkIds" + checkIds);
        String bz = ((QY_fwxmb_bzFragment) bzFragement).getBz();

        //家庭签约类型
        String strSignType="";



        JTYSCustomerDoctorCont cont = new JTYSCustomerDoctorCont();

        cont.setId(uuid);

        if(rb_qyinfo_type_personal.isChecked()){
            strSignType=SIGNTYPE_PERSONAL;
        }else if(rb_qyinfo_type_family.isChecked()){
            strSignType=SIGNTYPE_FAMILY;

            int sizeMembers= relationsMembers.size();
            if(sizeMembers>0){
                Log.e("家庭签约",sizeMembers+"");
                for(int i=0;i<sizeMembers;i++){
                    ARCHIVE_BASEINFO archiveBaseinfo= NovaApplication.fdbmanger.findAllByWhere(ARCHIVE_BASEINFO.class,"IDCARD='"+relationsMembers.get(i).getIDCARD()+"'").get(0);
                    archiveBaseinfo.setRELATIONID(relationsMembers.get(i).getRELATIONID());
                    archiveBaseinfo.setQYINFOID(uuid);
                    //签约数据
                    archiveBaseinfo.setDISTRICT_ID("1");
                    archiveBaseinfo.setIS_UPDATE("Y");
                    Log.e("TAG--sizeMembers--",archiveBaseinfo.toString());
                    NovaApplication.fdbmanger.updata(archiveBaseinfo,"IDCARD='"+relationsMembers.get(i).getIDCARD()+"'");

                }
            }

        }

        cont.setSigntype(strSignType);


        //家庭医生签约数据
        cont.setQysj(GlobalConts.getDateName(ed_date.getText().toString()));
        Log.e(TAG, "pos:" + pos_doc+"***"+NovaApplication.getDoctorList().get(pos_doc).getUSER_ID());
        cont.setQyys(NovaApplication.getDoctorList().get(pos_doc).getUSER_ID());
        cont.setQyysdh(doc_phone_edit.getText().toString());
        cont.setDetailId(checkIds);
        String datetimeNow = GlobalConts.datetimeFormat.format(new Date());
        cont.setUpdatedate(datetimeNow);
        cont.setUpdater(SPUtil.getStr_jdrno(this));
        cont.setCreatedate(datetimeNow);
        cont.setCreater(SPUtil.getStr_jdrno(this));
        cont.setSign("0");
        cont.setSource("0");
        cont.setBz(bz);
        cont.setCardNum(NovaApplication.getUserInfo().getIDCARD());
        cont.setCreaterorg(SPUtil.getStrjddwno(QYInfo.this));
        cont.setBeginservictime(GlobalConts.getDateName(ed_start_service.getText().toString()));
        cont.setRes2(GlobalConts.getDateName(ed_stop_serverce.getText().toString()));
        cont.setRes3(uuid);
        Log.w(TAG, cont.toString());
        if (flagSave == 0) {
            NovaApplication.fdbmanger.save(cont);

            showTextDialog("保存成功");
            // flagSave = 1;
            setFlagSave(1);
        } else {
            NovaApplication.fdbmanger.updata(cont, "cardNum='" + NovaApplication.getUserInfo().getIDCARD() + "'");
            showTextDialog("修改成功");
        }

//        userInfo.setDISTRICT_ID(cont.getId());
//        NovaApplication.fdbmanger.updata(userInfo);
        modifySignState(cont.getId());
        saveJTYSUserData();
        saveImgData();
    }

    /**
     * 比较开始时间和结束时间
     *
     * @param start 开始时间
     * @param stop  结束时间
     * @return true 开始时间大于结束时间    false 开始时间小于结束时间
     */
    private boolean compareData(String start, String stop) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        try {
            Date date1 = df.parse(GlobalConts.getDateName(start));
            Date date2 = df.parse(GlobalConts.getDateName(stop));

            if (date1.getTime() > date2.getTime()) {
                return true;
            } else {
                return false;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;

    }

    /**
     * 设置数据
     *
     * @author 王婷婷
     * @date 2017年6月1日 下午3:11:16
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void setDataContent() {

        if (userInfo != null) {

            String strQyDataSql = "";

            if (TextUtils.isEmpty(userInfo.getRELATIONID())) {
                //没有 家庭关系
                strQyDataSql = "cardNum='" + NovaApplication.getUserInfo().getIDCARD() + "'";
            } else {
                strQyDataSql = "id='" + userInfo.getQYINFOID() + "'";
            }

            ARCHIVE_BASEINFO baseInfo = null;

            //判断 是否签约 、是否有家庭关系
            if (TextUtils.isEmpty(userInfo.getDISTRICT_ID()) || TextUtils.isEmpty(userInfo.getRELATIONID())) {
                //未签约 或者是 户主
                baseInfo = userInfo;
            } else if (!TextUtils.isEmpty(userInfo.getRELATIONID())) {
                    String cardNum = "";
                    List<JTYSCustomerDoctorCont> conts = NovaApplication.fdbmanger.findAllByWhere(JTYSCustomerDoctorCont.class,
                            strQyDataSql);
                    if (conts.size() > 0) {
                        cardNum = conts.get(0).getCardNum();
                        List<ARCHIVE_BASEINFO> baseinfos = NovaApplication.fdbmanger.findAllByWhere(ARCHIVE_BASEINFO.class,
                                "IDCARD='" + cardNum + "'");
                        if (baseinfos.size() > 0) {
                            baseInfo = baseinfos.get(0);
                        }
                    }
            }

            if (baseInfo != null) {
                detail_id_tv.setText(baseInfo.getIDCARD());
                detail_name_text.setText(baseInfo.getCUSTOMERNAME());
                detail_nation_text.setText(baseInfo.getMINORITY());
                detail_date_tv.setText(df.format(baseInfo.getBIRTHDAY()));
                List<BD_DD_INFO> bdxingbie = NovaApplication.fdbmanger.findAllByWhereInInfoDB(BD_DD_INFO.class,
                        "PARENTID = 'DM01-08'");
                String sex = "";
                for (BD_DD_INFO bdi : bdxingbie) {
                    if (baseInfo.getSEX().equals(bdi.getID())) {
                        sex = bdi.getDATAINFO();
                    }
                }
                detail_sex_tv.setText(sex);
                detail_phone_edit.setText(baseInfo.getPHONE());
            }


//        List<JTYSCustomerDoctorCont> conts = NovaApplication.fdbmanger.findAllByWhere(JTYSCustomerDoctorCont.class,
//                "cardNum='" + NovaApplication.getUserInfo().getIDCARD() + "'");
            initQyData(strQyDataSql);

        }

    }

    /**
     * 初始化 读取签约数据
     * @param strQyDataSql
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void initQyData(String strQyDataSql) {
        List<JTYSCustomerDoctorCont> conts = NovaApplication.fdbmanger.findAllByWhere(JTYSCustomerDoctorCont.class,
                strQyDataSql);
        if (conts.size() > 0) {

            iv_photo1.setEnabled(false);
            iv_photo2.setEnabled(false);
            iv_photo3.setEnabled(false);
            // flagSave = 1;
            setFlagSave(1);
            cont = conts.get(0);
            if (cont.getHtbh() != null) {
                ht_no.setText(cont.getHtbh());
            }
            Log.w(TAG, "读取--" + cont.toString());
            ed_date.setText(TextUtils.isEmpty(cont.getQysj()) ? "" : GlobalContsJTYS.setDateName(cont.getQysj()));
            ed_date.showDialog(false);

            if (!TextUtils.isEmpty(cont.getQysj()) && TextUtils.isEmpty(cont.getBeginservictime())) {
                ed_start_service.setText(GlobalContsJTYS.setDateName(cont.getQysj()));
            } else {
                ed_start_service.setText(TextUtils.isEmpty(cont.getBeginservictime()) ? ""
                        : GlobalContsJTYS.setDateName(cont.getBeginservictime()));
            }

            ed_start_service.showDialog(false);

            if (!TextUtils.isEmpty(cont.getQysj()) && TextUtils.isEmpty(cont.getRes2())) {
                SimpleDateFormat sdfd = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
                try {
                    Date date = sdfd.parse(cont.getQysj());
                    Calendar calendar = new GregorianCalendar();
                    calendar.setTime(date);
                    calendar.add(calendar.YEAR, 1);
                    String format = sdfd.format(calendar.getTime());
                    ed_stop_serverce.setText(GlobalContsJTYS.setDateName(format));

                } catch (ParseException e) {
                    e.printStackTrace();
                }
            } else {
                ed_stop_serverce
                        .setText(TextUtils.isEmpty(cont.getRes2()) ? "" : GlobalContsJTYS.setDateName(cont.getRes2()));
            }

            if (SIGNTYPE_PERSONAL.equals(cont.getSigntype())) {
                rb_qyinfo_type_personal.setChecked(true);
            } else if (SIGNTYPE_FAMILY.equals(cont.getSigntype())) {
                rb_qyinfo_type_family.setChecked(true);
                String uuid = cont.getId();

                List<ARCHIVE_BASEINFO> baseinfos = NovaApplication.fdbmanger.findAllByWhere(ARCHIVE_BASEINFO.class,
                        "QYINFOID='" + uuid + "'");

                if (baseinfos != null) {
                    Log.e("eeeeeeQYINFOID", baseinfos.get(0).toString());
                    relationsMembers = baseinfos;
                    memberRelationAdapter.setDataList(relationsMembers, false);
                    memberRelationAdapter.notifyDataSetChanged();
                }
            }


            rb_qyinfo_type_family.setFocusable(false);
            rb_qyinfo_type_family.setEnabled(false);
            rb_qyinfo_type_personal.setFocusable(false);
            rb_qyinfo_type_personal.setEnabled(false);


            ed_stop_serverce.showDialog(false);
            doc_phone_edit.setText(cont.getQyysdh());
            doc_phone_edit.setEnabled(false);
            ed_sfysqm.setEnabled(false);
            ed_sfysqm.setClickable(false);
            if(NovaApplication.getDoctorList().size()>0){
                  for(int i=0;i<NovaApplication.getDoctorList().size();i++){
                      if(cont.getQyys().equals(NovaApplication.getDoctorList().get(i).getUSER_ID())){
                          ed_sfysqm.setSelection(i);
                      }
                  }

            }
            btn_save.setVisibility(View.GONE);
            btn_patientsign.setVisibility(View.GONE);
            btn_doctorsign.setVisibility(View.GONE);
            btn_add_photo.setVisibility(View.GONE);
            tv_add_family_member.setVisibility(View.GONE);

            initSignPhotoData(cont);

        } else {
            // flagSave = 0;
            setFlagSave(0);
        }
    }

    /**
     * 设置签名图片
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void initSignPhotoData(JTYSCustomerDoctorCont cont) {
//        List<JTYS_SignPictureData> pictures = NovaApplication.fdbmanger.findAllByWhere(JTYS_SignPictureData.class,
//                "CardNum = '" + userInfo.getIDCARD() + "'");
        List<JTYS_SignPictureData> pictures = NovaApplication.fdbmanger.findAllByWhere(JTYS_SignPictureData.class,
                "CardNum = '" + cont.getCardNum() + "'");

        Log("aa" + pictures.size());
        List<String> photoPaths = new ArrayList<String>();
        for (JTYS_SignPictureData pic : pictures) {
            Log("bb" + pic.type());
            switch (pic.type()) {
                case "1":// 医生签名
                    setSign(pic.getPhotoPath(), img_doctorsign);
                    btn_doctorsign.setVisibility(View.VISIBLE);
                    img_doctorsign.setVisibility(View.VISIBLE);
                    btn_doctorsign.setClickable(false);
                    break;
                case "2":// 患者签名
                    setSign(pic.getPhotoPath(), img_patientsign);
                    img_patientsign.setVisibility(View.VISIBLE);
                    btn_patientsign.setVisibility(View.VISIBLE);
                    btn_patientsign.setClickable(false);
                    break;
                case "3":// 其他照片
                    photoPaths.add(pic.getPhotoPath());
                    break;
                default:
                    break;
            }
        }
        for (int i = 0; i < photoPaths.size(); i++) {
            switch (i) {
                case 0:
                    setSign2(photoPaths.get(i), iv_photo1);
                    break;
                case 1:
                    setSign2(photoPaths.get(i), iv_photo2);
                    break;
                case 2:
                    setSign2(photoPaths.get(i), iv_photo3);
                    break;
            }
        }
    }

    public boolean hasServicePackage() {
        if (jcFragment.hasServicePackage() || dfxzFragment.hasServicePackage() || zzFragement.hasServicePackage()) {
            return true;
        }
        return false;
    }

    /**
     * 保存创建档案数据
     *
     * @author 王婷婷
     * @date 2017年7月26日 下午9:05:19
     */
    private void saveJTYSUserData() {
        try {

            List<JTYS_BASEINFO> jtysUsers = NovaApplication.fdbmanger.findAllByWhere(JTYS_BASEINFO.class,
                    "cardNum='" + userInfo.getIDCARD() + "'");
            if (jtysUsers.size() > 0) {
                // 本地数据已存在
                return;
            }

            final String sex = userInfo.getSEX().equals("DM01-08_1") ? "1" : "2";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            final String birthday = sdf.format(userInfo.getBIRTHDAY());

            String nation = "";
            String nationId = userInfo.getNATION();
            if (!TextUtils.isEmpty(nationId)) {
                List<BD_DD_INFO> minzuInfos = NovaApplication.fdbmanger.findAllByWhereInInfoDB(BD_DD_INFO.class,
                        "ID = " + "'" + nationId + "'");
                if (minzuInfos.size() > 0) {
                    nation = minzuInfos.get(0).getDATAINFO();
                }
            }
            final String str_jdrUserName = SPUtil.getStr_jdrno(QYInfo.this);// sp.getString("str_jdrUserName",
            // "");
            JTYS_BASEINFO info = new JTYS_BASEINFO();
            info.setID(GlobalContsJTYS.getUUID());
            info.setCardNum(userInfo.getIDCARD());
            info.setYsLoginNumber(str_jdrUserName);
            info.setName(userInfo.getCUSTOMERNAME());
            info.setSex(sex);
            info.setBirthday(birthday);
            info.setAddress(userInfo.getHOUSEHOLD_ADDR());
            info.setOfficeId(NovaApplication.getJgbh());

            info.setNation(nation);
            info.setSign("0");
            info.setSource("0");
            info.setPopulationType(userInfo.getPOPULATION_TYPE());
            info.setTel(userInfo.getPHONE());
            String datetimeNow = GlobalContsJTYS.datetimeFormat.format(new Date());
            info.setUpdatedate(datetimeNow);
            info.setUpdater(NovaApplication.getJgrno());
            info.setCreatedate(datetimeNow);
            info.setCreater(NovaApplication.getJgrno());
            NovaApplication.fdbmanger.save(info);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Spinner下拉
     *
     * @param pos
     * @author 王婷婷
     * @date 2017年4月26日 下午6:28:42
     */
    private void setSpinnerPos(int pos) {
        String user_mobile = NovaApplication.getDoctorList().get(pos).getMOBILE();
        Log.e(TAG, "setSpinnerPos:" + user_mobile);
        if (TextUtils.isEmpty(user_mobile)) {
            doc_phone_edit.setText("");
        } else {
            doc_phone_edit.setText(user_mobile);
        }

        try {
            Field field = AdapterView.class.getDeclaredField("mOldSelectedPosition");
            field.setAccessible(true); // 设置mOldSelectedPosition可访问
            field.setInt(ed_sfysqm, AdapterView.INVALID_POSITION); // 设置mOldSelectedPosition的值
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public int getFlagSave() {
        return flagSave;
    }

    public void setFlagSave(int flagSave) {
        this.flagSave = flagSave;
    }

    public void bindSpinnerQyDocList(List<BD_ORGANIZE_EMPLOYEE> bds) {
        // 判断当前城市在数组中的位置并显示
        QYDoctersAdapter adapter_bsc = new QYDoctersAdapter(getApplicationContext(), bds);
        // adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        ed_sfysqm.setAdapter(adapter_bsc);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent arg2) {
        super.onActivityResult(requestCode, resultCode, arg2);
        Log.e(TAG, "结果返回码：" + requestCode + "\n" + resultCode);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_PATIENT:
                    if (arg2.getExtras().containsKey("filePath")) {
                        strPatientSignPath = arg2.getExtras().getString("filePath");
                        setSign(strPatientSignPath, img_patientsign);
                        patientsign = "重签";
                    }
                    break;
                case REQUEST_CODE_DOCTOR:
                    if (arg2.getExtras().containsKey("filePath")) {
                        doctorsign = "重签";
                        strDocSignPath = arg2.getExtras().getString("filePath");
                        setSign(strDocSignPath, img_doctorsign);
                    }
                    break;
                case REQUEST_CODE_PHOTO:

                    String str_imgpath11 = mPhotoPath;

                    Intent intent = new Intent(QYInfo.this, ClipActivity1.class);
                    intent.putExtra("str_img", str_imgpath11);
                    startActivityForResult(intent, 0);

                    break;
                case 0:
                    if (lstPhotoPaths == null) {
                        lstPhotoPaths = new ArrayList<String>();
                    }
                    lstPhotoPaths.add(mPhotoPath);
                    if (lstPhotoPaths.size() == 1) {
                        // setSign(arg2, iv_photo1, mPhotoPath);s
                        iv_bg.setVisibility(View.GONE);
                        iv_photo1.setVisibility(View.VISIBLE);
                        iv_photo1.setBackground(new BitmapDrawable(null, ImageTools.readBitmapAutoSize(mPhotoPath)));
                    } else if (lstPhotoPaths.size() == 2) {
                        iv_bg.setVisibility(View.GONE);
                        // setSign(arg2, iv_photo2, mPhotoPath);
                        iv_photo1.setVisibility(View.VISIBLE);
                        iv_photo2.setVisibility(View.VISIBLE);
                        iv_photo2.setBackground(new BitmapDrawable(null, ImageTools.readBitmapAutoSize(mPhotoPath)));
                    } else if (lstPhotoPaths.size() == 3) {
                        iv_bg.setVisibility(View.GONE);
                        // setSign(arg2, iv_photo3, mPhotoPath);
                        iv_photo1.setVisibility(View.VISIBLE);
                        iv_photo2.setVisibility(View.VISIBLE);
                        iv_photo3.setVisibility(View.VISIBLE);
                        iv_photo3.setBackground(new BitmapDrawable(null, ImageTools.readBitmapAutoSize(mPhotoPath)));
                    }

                    break;
                case REQUEST_CODE_ADD_MEMBER:
                    if (arg2.getExtras().containsKey("relation")) {
                        ARCHIVE_BASEINFO relationUser=(ARCHIVE_BASEINFO)arg2.getExtras().getSerializable("relation");
                        Log.e("relation",relationUser.toString());
                        if(relationsMembers==null){
                            relationsMembers=new ArrayList<>();
                        }else{
                            if(userInfo.getIDCARD().equals(relationUser.getIDCARD())){
                                showTextDialog("不能选择本人");
                                return;
                            }
                            for(ARCHIVE_BASEINFO baseinfo:relationsMembers){
                                if(baseinfo.getIDCARD().equals(relationUser.getIDCARD())){
                                    showTextDialog("家庭成员已存在");
                                    return;
                                }
                            }
                            //默认选择值是配偶
                            relationUser.setRELATIONID("DM01-06_8");
                            relationsMembers.add(relationUser);
                            memberRelationAdapter. setDataList(relationsMembers,true);
                            memberRelationAdapter.notifyDataSetChanged();
                            Log.e("relation--size","tt"+relationsMembers.size());
                        }

                    }
                    break;
                default:
                    break;
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void setSign2(String imgPath, ImageView v) {
        // String result = "";
        btn_add_photo.setVisibility(View.VISIBLE);
        btn_add_photo.setClickable(false);
        iv_bg.setVisibility(View.GONE);
        if (!TextUtils.isEmpty(imgPath)) {
            v.setVisibility(View.VISIBLE);
            Log.e(TAG, "照片src：" + imgPath);
            File file = new File(imgPath);
            if (file.exists()) {
                // v.setbacImageBitmap(ImageTools.readBitmapAutoSize(imgPath));
                v.setVisibility(View.VISIBLE);
                v.setBackground(new BitmapDrawable(null, ImageTools.readBitmapAutoSize(imgPath)));
            } else {
                v.setImageBitmap(null);
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void setSign(String imgPath, ImageView v) {
        // String result = "";

        if (!TextUtils.isEmpty(imgPath)) {
            Log.e(TAG, "照片src：" + imgPath);
            File file = new File(imgPath);
            if (file.exists()) {
                // v.setbacImageBitmap(ImageTools.readBitmapAutoSize(imgPath));
                v.setVisibility(View.VISIBLE);
                v.setBackground(new BitmapDrawable(null, ImageTools.readBitmapAutoSize(imgPath)));
            } else {
                v.setImageBitmap(null);
            }
        }
    }

    /**
     * 是否删除图片
     *
     * @author 王婷婷
     * @date 2017年12月7日 下午1:03:42
     */
    private void isDeleteImgFile() {
        List<JTYS_SignPictureData> jtysUsers = NovaApplication.fdbmanger.findAllByWhere(JTYS_SignPictureData.class,
                "cardNum='" + userInfo.getIDCARD() + "'");
        if (jtysUsers == null) {
            // Environment.getExternalStorageDirectory() +
            // String path = GlobalConts.SIGN_FILENAME_FOLDER;
            deleteDirectoryFile(signPath, userInfo.getIDCARD());
            deleteDirectoryFile(imagePath, userInfo.getIDCARD());
        } else {
            if (jtysUsers.size() == 0) {
                // Environment.getExternalStorageDirectory() +
                String path = GlobalConts.SIGN_FILENAME_FOLDER;
                deleteDirectoryFile(path, userInfo.getIDCARD());
            }

        }
    }

    /**
     * 删除指定 目录下的指定文件
     *
     * @param filePath 被删除目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public boolean deleteDirectoryFile(String filePath, String cardNum) {
        boolean flag = false;
        // 如果filePath不以文件分隔符结尾，自动添加文件分隔符
        if (!filePath.endsWith(File.separator)) {
            filePath = filePath + File.separator;
        }
        File dirFile = new File(filePath);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        flag = true;
        File[] files = dirFile.listFiles();
        // 遍历删除文件夹下的所有文件(包括子目录)
        for (int i = 0, len = files.length; i < len; i++) {

            if (files[i].isFile()) {
                Log.e(TAG, "files[i].isFile():" + files[i].getName());
                if (files[i].getName().contains(cardNum)) {
                    // 删除子文件
                    flag = deleteFile(files[i].getAbsolutePath());
                    if (!flag) {
                        break;
                    }
                }
            } else {
                // 删除子目录
                flag = deleteDirectoryFile(files[i].getAbsolutePath(), cardNum);
                if (!flag) {
                    break;
                }
            }
        }
        return flag;
        // if (!flag)
        // return false;
        // // 删除当前空目录
        // return dirFile.delete();
    }

    private void Log(String s) {
        System.out.println("qyinfoimg" + s);
    }

    /**
     * 保存图片信息所有的
     *
     * @author 王婷婷
     * @date 2017年12月7日 下午3:36:59
     */
    private void saveImgData() {
        Log.e("保存图片",strPatientSignPath+"***"+strDocSignPath+"+++"+lstPhotoPaths.size());
        // 保存签名图片
        if (TextUtils.isEmpty(strPatientSignPath)) {
        } else {
            /// storage/emulated/0/PublicHealth/Sign/370883198806046521_2017-12-07_1__20171207161645_8987.png
            String[] strs = strPatientSignPath.split("/");

            saveImgDataSingle(strs[strs.length - 1].toString(), strPatientSignPath, "1");
        }

        if (TextUtils.isEmpty(strDocSignPath)) {
        } else {
            /// storage/emulated/0/PublicHealth/Sign/370883198806046521_2017-12-07_1__20171207161645_8987.png
            String[] strs = strDocSignPath.split("/");
            saveImgDataSingle(strs[strs.length - 1].toString(), strDocSignPath, "0");
        }
        // 保存拍照图片
        for (String path : lstPhotoPaths) {
            String[] strs = path.split("/");
            saveImgDataSingle(strs[strs.length - 1].toString(), path, "2");
        }
    }

    /**
     * 保存图片信息单张
     *
     * @author 王婷婷
     * @date 2017年12月7日 下午3:36:59
     */
    private void saveImgDataSingle(String imgName, String imgPath, String str_type) {
        JTYS_SignPictureData info = new JTYS_SignPictureData();
        info.setID(GlobalContsJTYS.getUUID());
        info.setCardNum(userInfo.getIDCARD());
        info.setYsLoginNumber(SPUtil.getStr_jdrno(QYInfo.this));

        info.setPhotoName(imgName);
        info.setPhotoPath(imgPath);
        info.setCreateOrgId(NovaApplication.getJgbh());
        String datetimeNow = GlobalContsJTYS.datetimeFormat.format(new Date());
        info.setCreatetime(datetimeNow);
        info.setCreaterId(SPUtil.getStr_jdrno(this));
        info.setSign("0");
        info.setSource("0");
        info.setIsUpdate("Y");// Y未上传 N已上传
        info.setRes0(str_type);
        info.setRes1(uuid);
        List<JTYS_SignPictureData> pictures = NovaApplication.fdbmanger.findAllByWhere(JTYS_SignPictureData.class,
                "CardNum = '" + userInfo.getIDCARD() + "'");
        String type = JTYS_SignPictureData.type(imgPath);
        for (JTYS_SignPictureData data : pictures) {
            if (data.type() == type) {
                NovaApplication.fdbmanger.delete(data);
                try {
                    File f = new File(data.getPhotoPath());
                    if (f.exists()) {
                        f.delete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        NovaApplication.fdbmanger.save(info);
    }

    private String mPhotoPath;

    @Override
    public boolean onLongClick(View v) {
        switch (v.getId()) {
            case R.id.iv_photo1:
                showDeleteDialog(0);
                break;
            case R.id.iv_photo2:
                showDeleteDialog(1);
                break;
            case R.id.iv_photo3:
                showDeleteDialog(2);
                break;

            default:
                break;
        }
        return true;
    }

    /**
     * 显示删除提示框
     */
    private void showDeleteDialog(final int i) {
        new CommomDialog(this, R.style.dialog, "", new CommomDialog.OnCloseListener() {

            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    switch (i) {
                        case 0:
                            iv_photo1.setVisibility(View.GONE);
                            deletePhotoFromSD(0);
                            break;
                        case 1:
                            iv_photo2.setVisibility(View.GONE);
                            deletePhotoFromSD(1);
                            break;
                        case 2:
                            iv_photo3.setVisibility(View.GONE);
                            deletePhotoFromSD(2);
                            break;

                        default:
                            break;
                    }
                    dialog.dismiss();
                }

            }

        }).setTitle("是否删除图片").setPositiveButton("删除").setNegativeButton("取消").show();

    }

    /**
     * 删除存储在sd上的文件
     *
     * @param i
     */
    protected void deletePhotoFromSD(int i) {
        String path = "";
        if (lstPhotoPaths != null && lstPhotoPaths.size() > 0) {
            if (i == lstPhotoPaths.size()) {
                i = lstPhotoPaths.size() - 1;
            }
            if (i == 2 && lstPhotoPaths.size() == 1) {
                i = 0;
            }
            path = lstPhotoPaths.get(i);
            lstPhotoPaths.remove(i);
        }
        judgeFileIsExistsAndDelete(path);

    }

    /**
     * 判断该路径下文件是否存在，存在就删除
     *
     * @param path
     */
    private void judgeFileIsExistsAndDelete(String path) {
        if (!TextUtils.isEmpty(path)) {
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            }
        }
    }

    /**
     * 删除不再使用的图片
     */
    protected void deleteCachePhotoFromSD() {
        judgeFileIsExistsAndDelete(strDocSignPath);
        judgeFileIsExistsAndDelete(strPatientSignPath);
        if (lstPhotoPaths != null && lstPhotoPaths.size() > 0) {
            for (int i = 0; i < lstPhotoPaths.size(); i++) {
                deletePhotoFromSD(i);
            }
        }

    }


    /**
     * 家庭成员关系删除
     * @param deletePosition
     */
    @Override
    public void deletePosition(int deletePosition) {
        if(relationsMembers!=null){
            if(relationsMembers.size()>0){
                relationsMembers.remove(deletePosition);
                memberRelationAdapter.setDataList(relationsMembers,true);
                memberRelationAdapter.notifyDataSetInvalidated();
            }
        }

    }
    /**
     * 家庭成员关系修改
     * @param updatePosition
     */
    @Override
    public void updatePosition(int updatePosition ,ARCHIVE_BASEINFO memberInfo) {
        Log.e("updatePosition------",memberInfo.toString());
        relationsMembers.set(updatePosition,memberInfo);

    }


    /**
     * 保存之后 更改签约状态
     */
    public void modifySignState(String qyid) {

        List<ARCHIVE_BASEINFO> idCardList = NovaApplication.fdbmanger.findAllByWhere(ARCHIVE_BASEINFO.class,
                "IDCARD = '" + userInfo.getIDCARD() + "'");
        ARCHIVE_BASEINFO userinfo11 = idCardList.get(0);
        userinfo11.setDISTRICT_ID("1");
        userinfo11.setIS_UPDATE("Y");
        NovaApplication.fdbmanger.updata(userinfo11);
        userInfo = userinfo11;
        NovaApplication.setUserInfo(userInfo);

        Log.e("QYInfo",userInfo.toString());

    }
}